<template>
  <ProgressBar
    :value="fileStore.schedule"
    v-if="fileStore.schedule"
  ></ProgressBar>

  <div>
    <div
      class="flex flex-col items-center pt-[50px]"
      v-if="!flagStore.isPreviewerOpen"
    >
      <div class="mb-[60px]">
        <img :src="logo" alt="" class="w-[70px] h-[70px]" />
      </div>
      <div class="">
        <!-- <img :src="data.url" class="w-[180px] h-[127px]" /> -->
        <div class="w-full">
          <div class="relative mx-auto">
            <div
              v-if="data.type === 'folder'"
              class="mt-3 mb-5 inline-block scale-150 transform lg:mt-2 lg:mb-8"
            >
              <div class="svg-color-theme">
                <SvgIcon
                  name="folder"
                  :style="{ width: '53px', height: '52px' }"
                  iconClass="svg-color-theme"
                />
              </div>
            </div>

            <div
              v-else-if="data.type === 'image'"
              class="relative mb-4 inline-block h-24 w-28 lg:h-28 lg:w-36"
            >
              <img
                :src="data.url"
                alt=""
                loading="lazy"
                class="h-full w-full rounded-lg object-cover shadow-lg"
              />
            </div>
            <div
              v-else-if="data.type === 'video'"
              class="relative mb-4 inline-block h-24 w-28 lg:h-28 lg:w-36"
            >
              <video
                :src="item.url"
                class="h-full w-full rounded-lg object-cover shadow-lg"
                loop
                muted
                @loadeddata="
                  (e) => {
                    e.target.volume = 0;
                    e.target.play();
                  }
                "
              />
            </div>
            <div
              v-else
              class="flex items-center justify-center z-0 mt-5 mb-10 scale-125 transform lg:mb-12 lg:mt-6 lg:scale-150"
            >
              <span
                class="text-theme-color absolute z-[5] mx-auto mt-1 inline-block w-7 overflow-hidden text-ellipsis text-center text-[9px] font-semibold"
              >
                {{ data.type }}
              </span>
              <SvgIcon
                name="file"
                svgClass="vue-feather dark:text-gray-800 text-gray-100 "
                :style="{ width: '38px', height: '51px' }"
                iconClass="svg-color-theme"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="mb-[20px] text-[#333333] text-[18px]">{{ data.name }}</div>
      <div class="flex justify-center mb-[45px] w-[100%]">
        <div class="mr-[26px]">
          {{
            i18nStore.translate('file_size') + '：' + formatFileSize(data.size)
          }}
        </div>
        <div>
          {{
            i18nStore.translate('expiration_time') +
            '：' +
            parseTime(data.expire_time)
          }}
        </div>
      </div>
      <!-- 登录 -->
      <div class="sm:flex justify-center mb-[73px] hidden">
        <div class="text-[#5CD6C8] text-[16px] cursor-pointer font-bold">
          <router-link to="/login">{{
            i18nStore.translate('quick_login')
          }}</router-link>
        </div>
        <div class="px-[20px] text-[#B5C3C1]">|</div>
        <div class="text-[#5CD6C8] text-[16px] cursor-pointer font-bold">
          <router-link to="/register">{{
            i18nStore.translate('register_account')
          }}</router-link>
        </div>
      </div>
      <!-- 按钮 -->
      <div class="flex justify-center mb-[102px]">
        <Button
          type="button"
          :label="i18nStore.translate('download_to_local')"
          icon="pi pi-download"
          :loading="loading"
          @click="downloadFile"
          class="px-[22px] py-[16px] rounded-xl border text-[#5CD6C8] border-[#5CD6C8] mr-5"
        />
        <Button
          type="button"
          :label="i18nStore.translate('transfer_to_cloud_storage')"
          icon="pi pi-download"
          :loading="loading1"
          @click="deposit"
          class="px-[22px] py-[16px] rounded-xl border bg-[#5CD6C8] text-white"
        />
      </div>
      <!-- tips -->
      <div
        class="sm:w-[540px] w-[100%] sm:ml-[0] sm:h-[100px] sm:pl-[26px] pl-[24px] sm:pt-[24px] relative"
      >
        <div
          class="text-[#333333] sm:text-[24px] text-[16px] mb-[14px] font-bold"
        >
          {{ i18nStore.translate('title') }}
        </div>
        <div class="text-[#666666] sm:text-[15px] text-[12px]">
          {{ i18nStore.translate('title2') }}
        </div>
        <div
          class="absolute sm:right-[-65px] right-[0px] top-[50%] translate-y-[-50%] flex justify-center items-center w-[130px] h-[50px] bg-[#5CD6C8] rounded-[25px] sm:text-[18px] text-[16px] text-[#fff]"
        >
          <router-link to="/index"
            >{{ i18nStore.translate('user_it') }} ></router-link
          >
        </div>
      </div>
      <!-- toast -->
      <Toast position="top-center" group="loginResult" />
    </div>

    <Preview v-else />
  </div>
</template>
<script setup>
import Toast from 'primevue/toast';
import {
  useFlagStore,
  useFileStore,
  useToastStore,
  useI18nStore,
  useUserInfoStore
} from '@/stores';
import { shareFileDetail, addFile } from '@/apis/file';
import logo from '@/assets/icons/logo.svg';
import { useToast } from 'primevue/usetoast';
const userInfoStore = useUserInfoStore();
const { okCloudDiskToken } = storeToRefs(userInfoStore);
const toastStore = useToastStore();
const i18nStore = useI18nStore();
const route = useRoute();
const router = useRouter();
const toast = useToast();
const id = atob(route.params.id);
// const time = route.query.expire_time;
const data = ref({});

function getFileDetail() {
  shareFileDetail({ share_id: id }).then((res) => {
    const fileType = getFileType('.' + res.data[FILE_LIST.EXT]);
    const type =
      fileType.type === 'image'
        ? 'image'
        : fileType.extension === 'unknown_type'
        ? ''
        : fileType.extension;
    const Type = res.data.type;
    data.value = { ...res.data, type, Type };
    document.title = data.value.name + ' - OK云盘 - 您的文件存储解决方案';
  });
}
const loading = ref(false);
const loading1 = ref(false);

function downloadFile() {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 2000);
  fileStore.getdownloadPoints(data.value).then((res) => {
    if (res) {
      download(data.value);
    } else {
      toast.add({
        severity: 'error',
        summary: i18nStore.translate(
          'insufficient_download_remaining_please_recharge_to_download'
        ),
        detail: '',
        group: 'loginResult',
        life: 1500
      });
    }
  });
}

async function download(fileInfo) {
  if (!fileInfo.url) return;
  const blob = await http(fileInfo.url, { responseType: 'blob' });
  const a = document.createElement('a');
  const url = URL.createObjectURL(blob);
  a.href = url;
  a.download = fileInfo.name;
  a.click();
  URL.revokeObjectURL(url);
  toast.add({
    severity: 'success',
    summary: 'success',
    detail: '',
    group: 'loginResult',
    life: 1500
  });
  return true;
}
function deposit() {
  loading1.value = true;
  setTimeout(() => {
    loading1.value = false;
  }, 1500);
  if (okCloudDiskToken.value) {
    addFile({
      name: data.value.name,
      url: removeFirstOccurrence(data.value.url, 'https://down.okpan.fun/'),
      size: data.value.size,
      ext: data.value.ext,
      folder_id: 0,
      icon: removeFirstOccurrence(data.value.icon, 'https://down.okpan.fun/'),
      type: 1
    }).then((res) => {
      if (res.status == 0) {
        router.push('/myFiles');
        toastStore.showToast({
          severity: 'success',
          summary: 'Success Message',
          detail: res.message,
          life: 2000,
          group: 'upload_success'
        });
      } else {
        toastStore.showToast({
          severity: 'error',
          summary: 'Error Message',
          detail: res.message,
          life: 999999,
          group: 'upload_failed'
        });
      }
    });
  } else {
    router.push('/login');
  }
}

function removeFirstOccurrence(str, subStr) {
  const index = str.indexOf(subStr);
  if (index !== -1) {
    return str.slice(0, index) + str.slice(index + subStr.length);
  }
  return str;
}
const flagStore = useFlagStore();
const fileStore = useFileStore();
const FILE_LIST = {
  FILE_ID: 'file_id',
  FOLDER_ID: 'folder_id',
  FOLDER_ITEMS: 'folder_items',
  CREATE_TIME: 'create_time',
  SIZE: 'size',
  EXT: 'ext',
  IMG_URL: 'url',
  IMG_THUMB: 'icon'
};
const tempData = {
  file_id: 249,
  name: 'b2d3f6015e7fb75f5a2d4c877b8fc877_1.jpg',
  url: 'https://down.okpan.fun/test/687f0ca36ace5b57b133607e665bd999_b2d3f6015e7fb75f5a2d4c877b8fc877_1.jpg',
  size: '21373.00',
  ext: 'jpg',
  user_id: 1,
  folder_id: 0,
  create_time: '2024-03-20 16:00:08',
  update_time: '2024-03-20 16:00:08',
  is_del: 0,
  icon: 'https://down.okpan.fun/test/687f0ca36ace5b57b133607e665bd999_b2d3f6015e7fb75f5a2d4c877b8fc877_1.jpg'
};
// 处理文件参数
const handleFileData = (file) => {
  const fileType = getFileType('.' + file[FILE_LIST.EXT]);
  const type =
    fileType.type === 'image'
      ? 'image'
      : fileType.extension === 'unknown_type'
      ? ''
      : fileType.extension;
  const size = formatFileSize(file[FILE_LIST.SIZE]);
  const times = file[FILE_LIST.CREATE_TIME];
  // const url = file[FILE_LIST.IMG_URL].replace('https', 'http')
  const url = file[FILE_LIST.IMG_URL];
  return {
    ...file,
    type,
    size,
    times,
    url,
    fileType
  };
};
// 双击预览
const clickHandle = (item) => {
  console.log('click');
  const fileData = handleFileData(tempData);
  if (fileStore.checkIsFile(fileData)) {
    // 文件触发预览
    flagStore.setPreviewerOpen(true);
    fileStore.setCurFileInfo(fileData);
  } else if (fileStore.checkIsFolder(fileData)) {
    // 文件夹触发进入
    flagStore.setFileListLoading(true);
    fileStore.entryFolder(fileData[FILE_LIST.FOLDER_ID]).then(() => {
      flagStore.setFileListLoading(false);
    });
  }
};
onMounted(() => {
  getFileDetail();
});
</script>
<style lang="scss" scoped></style>
